package com.kk.config;


import com.kk.handlers.JwtAccessDeniedHandler;
import com.kk.handlers.JwtAuthenticationEntryPoint;
import com.kk.handlers.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

/**
 * Spring Security 安全配置类
 * 整合JWT认证、授权、异常处理等功能
 *
 * @author kl
 * @version 1.0
 * @date 2025/10/15
 */
@Configuration
@EnableMethodSecurity  // 启用方法级别的安全注解 @PreAuthorize, @PostAuthorize等
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;



    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // ========== 授权配置 ==========
                .authorizeHttpRequests(auth -> auth
                        // 公开接口 - 无需认证
                        .requestMatchers(
                                "/user/login",
                                "/user/register",
                                "/druid/**",
                                "/captcha/**",
                                "/doc.html",
                                "/webjars/**",
                                "/swagger-resources/**",
                                "/v3/api-docs/**"
                        ).permitAll()

                        // 静态资源 - 无需认证
                        .requestMatchers(
                                "/static/**",
                                "/css/**",
                                "/js/**",
                                "/images/**",
                                "/favicon.ico"
                        ).permitAll()

                        // 其他所有请求都需要认证
                        .anyRequest().authenticated()
                )

                // ========== 会话管理 ==========
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 无状态会话（JWT模式）
                )

                // ========== 添加JWT认证过滤器 ==========
                // 在UsernamePasswordAuthenticationFilter之前执行
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)

                // ========== 异常处理 ==========
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)  // 未认证处理
                        .accessDeniedHandler(jwtAccessDeniedHandler)            // 无权限处理
                )

                // ========== CORS配置 ==========
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))

                // ========== 禁用不需要的功能 ==========
                .formLogin(AbstractHttpConfigurer::disable)      // 禁用表单登录
                .httpBasic(AbstractHttpConfigurer::disable)      // 禁用HTTP Basic认证
                .csrf(AbstractHttpConfigurer::disable)           // 禁用CSRF（RESTful API通常不需要）
                .logout(AbstractHttpConfigurer::disable);        // 禁用默认登出（使用自定义登出）

        return http.build();
    }

    /**
     * CORS跨域配置
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        // 允许的源（生产环境应该配置具体的域名）
        configuration.setAllowedOriginPatterns(List.of("*"));

        // 允许的HTTP方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));

        // 允许的请求头
        configuration.setAllowedHeaders(List.of("*"));

        // 允许携带认证信息（cookies）
        configuration.setAllowCredentials(true);

        // 预检请求的有效期（秒）
        configuration.setMaxAge(3600L);

        // 暴露的响应头
        configuration.setExposedHeaders(Arrays.asList("Authorization", "Content-Disposition"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
